#include "widget.h"
#include "ui_widget.h"

#include "QSqlDatabase"
#include "QSqlDriver"

#include "qdebug.h"
#include "qsqlquery.h"

#include "qfiledialog.h"
#include "qstringlist.h"

#include "qdebug.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
//    connect()


    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");

//    db.setHostName("210.30.157.180");
//    db.setDatabaseName("sci");
//    db.setUserName("sa");
//    db.setPassword("depond");
//    db.setHostName("localhost");
//    QFileDialog sqlite_db;
//    sqlite_db.setNameFilter("Sqlite3 database files (*.db)");
    QString db_file;// = "isucalc_fs.db";
//        db_file = QFileDialog::getOpenFileName(this, tr("Open Database"),
//                                               "",
//                                               tr("Sqlite3 database files (*.db)"));
    QFileDialog db_FileDialog;//(this);
    if(db_FileDialog.exec())
    {
//        db_FileDialog.Accepted;
        db_file = db_FileDialog.selectedFiles().takeFirst();
    }
    if(!db_file.isEmpty())
        db.setDatabaseName(db_file.toAscii());
    else
        db.setDatabaseName(":memory");
    db.setUserName("");
    db.setPassword("");
    sqlmod=new QSqlQueryModel;
    table_mod = new QStringListModel(this);
    field_mod = new QStringListModel(this);
    view_mod = new QStringListModel(this);

    if(db.open()==true)
    {
        ui->tableView->setModel(sqlmod);
        table_mod->setStringList(db.tables(QSql::Tables ));
        ui->list_table->setModel(table_mod);
        view_mod->setStringList(db.tables(QSql::Views ));
        ui->list_view->setModel(view_mod);
    }
//delete tb;
}

Widget::~Widget()
{
    delete ui;
    delete table_mod;
    delete field_mod;
    delete view_mod;
    //QSqlDatabase db = QSqlDatabase::database();

}

void Widget::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

bool Widget::ExecSQL()
{
    sqlmod->setQuery(ui->plainTextEdit_2->toPlainText().toAscii());
return true;
}

void Widget::tableChanged()
{
//    qDebug()<<ui->list_table->model()->itemData(ui->list_table->currentIndex());
//    qmodelindex
    QStringList lfld;
    QString sfld="PRAGMA table_info(\'%1\')";
    QSqlQuery qfld;

    qfld.exec(sfld.arg(ui->list_table->model()->data(ui->list_table->currentIndex(),Qt::DisplayRole).toString()));
    while(qfld.next())
    {
        lfld<<qfld.value(1).toString();
    }
    field_mod->setStringList(lfld);
    ui->list_field->setModel(field_mod);

}

void Widget::RefetchTable()
{
    QSqlDatabase db = QSqlDatabase::database();
    table_mod->setStringList(db.tables(QSql::Tables ));
    view_mod->setStringList(db.tables(QSql::Views));
}
